package com.block.api.controller.page;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.factory.PushApiFactory;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.db.entity.*;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.MerchantBaseInfoMapper;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.match.service.IDataMatchOrderInfoService;
import com.block.match.service.IDataMatchOrderItemService;
import com.block.merchant.service.IMerchantBaseInfoService;
import com.market.member.service.IMemberBaseInfoService;
import com.market.member.service.IMemberSourceInfoService;
import org.apache.commons.lang3.StringUtils;
import org.jboss.marshalling.ObjectTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("page")
public class PageController {

    @Autowired
    IDataMatchOrderInfoService dataMatchOrderInfoService;
    @Autowired
    IMemberSourceInfoService memberSourceInfoService;
    @Autowired
    IDataMatchOrderItemService dataMatchOrderItemService;
    @Autowired
    IMerchantBaseInfoService merchantBaseInfoService;
    @Resource
    MemberSourceInfoMapper memberSourceInfoMapper;
    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;

    @RequestMapping(value = "/source.html")
    public String source(){
        return "source";
    }


    /**
     * 用户协议
     */
    @RequestMapping(value = "/newprotocol/{orderId}/{orderItemIds}.html")
    public String newprotocol(@PathVariable("orderId") String orderId,
                               @PathVariable("orderItemIds") String orderItemIds,
                               ModelMap modelMap){

        DataMatchOrderInfo matchOrderInfo = dataMatchOrderInfoService.getById(orderId);

        List<String> orderItemIdList = JSON.parseArray(JSON.toJSONString(orderItemIds.split("-")), String.class);

        List<Map<String, String>> mapList = new ArrayList<>();
        for (String itemId : orderItemIdList) {

            DataMatchOrderItem matchOrderItem = dataMatchOrderItemService.getById(itemId);
            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(matchOrderItem.getInfoId());

            Map<String, String> itemMap = new HashMap<>();
            itemMap.put("companyName", merchantBaseInfo.getCompanyName());
            itemMap.put("companyId", String.valueOf(merchantBaseInfo.getId()));

            if (StrUtil.equals(matchOrderItem.getInfoType(), "APIS")){
                // 查询双授权 的 商户机构信息
                MerchantThirdBaseInfo thirdBaseInfo = merchantThirdBaseInfoService.selectEntityByOrderNo(matchOrderItem.getPushId());
                if (ObjectUtil.isNotEmpty(thirdBaseInfo)){
                    String productInfo = StrUtil.format("{} | {}", thirdBaseInfo.getProductId(), thirdBaseInfo.getProductName());
                    itemMap.put("productInfo", productInfo);
                }
            }
            mapList.add(itemMap);
        }

        MemberSourceInfo memberSourceInfo = memberSourceInfoService.getById(matchOrderInfo.getUid());

        if (ObjectUtil.isNotEmpty(memberSourceInfo)){
            modelMap.put("uid", String.valueOf(memberSourceInfo.getUid()));
            modelMap.put("username", DesensitizedUtil.chineseName(memberSourceInfo.getRealname()));
            modelMap.put("idcard", DesensitizedUtil.idCardNum(memberSourceInfo.getIdcard(), 3,3));
            if (StringUtils.isNotEmpty(memberSourceInfo.getMobile())){
                modelMap.put("mobile", memberSourceInfo.getMobile());
            }else {
                modelMap.put("mobile", "");
            }
        }

//        modelMap.put("mobile", DesensitizedUtil.mobilePhone(memberSourceInfo.getMobile()));
        modelMap.put("datetime", LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME));

//        modelMap.put("orderId", orderId);
        modelMap.put("itemMapList", mapList);

        return "newprotocol";
    }

    /**
     * 用户协议（金耀花）
     */
    @RequestMapping(value = "/newprotocol/{infoId}/{orderId}/{orderItemIds}.html")
    public String newprotocolJinYaoHua(@PathVariable("infoId") String infoId,
                                       @PathVariable("orderId") String orderId,
                              @PathVariable("orderItemIds") String orderItemIds,
                              ModelMap modelMap){

        DataMatchOrderInfo matchOrderInfo = dataMatchOrderInfoService.getById(orderId);
        MerchantBaseInfo merchantBaseInfo1 = merchantBaseInfoMapper.selectById(infoId);

        List<String> orderItemIdList = JSON.parseArray(JSON.toJSONString(orderItemIds.split("-")), String.class);

        List<Map<String, String>> mapList = new ArrayList<>();
        for (String itemId : orderItemIdList) {

            DataMatchOrderItem matchOrderItem = dataMatchOrderItemService.getById(itemId);
            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(matchOrderItem.getInfoId());

            Map<String, String> itemMap = new HashMap<>();
            itemMap.put("companyName", merchantBaseInfo.getCompanyName());
            itemMap.put("companyId", String.valueOf(merchantBaseInfo.getId()));

            if (StrUtil.equals(matchOrderItem.getInfoType(), "APIS")){
                // 查询双授权 的 商户机构信息
                MerchantThirdBaseInfo thirdBaseInfo = merchantThirdBaseInfoService.selectEntityByOrderNo(matchOrderItem.getPushId());
                if (ObjectUtil.isNotEmpty(thirdBaseInfo)){
                    String productInfo = StrUtil.format("{} | {}", thirdBaseInfo.getProductId(), thirdBaseInfo.getProductName());
                    itemMap.put("productInfo", productInfo);
                }
            }
            mapList.add(itemMap);
        }

        MemberSourceInfo memberSourceInfo = memberSourceInfoService.getById(matchOrderInfo.getUid());

        if (ObjectUtil.isNotEmpty(memberSourceInfo)){
            modelMap.put("uid", String.valueOf(memberSourceInfo.getUid()));
            modelMap.put("username", DesensitizedUtil.chineseName(memberSourceInfo.getRealname()));
            modelMap.put("idcard", DesensitizedUtil.idCardNum(memberSourceInfo.getIdcard(), 3,3));
            if (StringUtils.isNotEmpty(memberSourceInfo.getMobile())){
                modelMap.put("mobile", memberSourceInfo.getMobile());
            }else {
                modelMap.put("mobile", "");
            }
        }

//        modelMap.put("mobile", DesensitizedUtil.mobilePhone(memberSourceInfo.getMobile()));
        modelMap.put("datetime", LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME));

//        modelMap.put("orderId", orderId);
        modelMap.put("itemMapList", mapList);
        if (StrUtil.equals("370", infoId)){
            modelMap.put("companyTitle", merchantBaseInfo1.getCompanyTitle());
        }

        return "newprotocol";
    }

    /**
     * 用户协议
     */
    @RequestMapping(value = "/protocol/{orderId}/{orderItemIds}.html")
    public String userProtocol(@PathVariable("orderId") String orderId,
                       @PathVariable("orderItemIds") String orderItemIds,
                       ModelMap modelMap){

        // TODO: 2023/8/23 访问条件判断

        DataMatchOrderInfo matchOrderInfo = dataMatchOrderInfoService.getById(orderId);

        List<String> orderItemIdList = JSON.parseArray(JSON.toJSONString(orderItemIds.split("-")), String.class);

        List<Map<String, String>> mapList = new ArrayList<>();
        for (String itemId : orderItemIdList) {

            DataMatchOrderItem matchOrderItem = dataMatchOrderItemService.getById(itemId);
            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(matchOrderItem.getInfoId());

            Map<String, String> itemMap = new HashMap<>();
            itemMap.put("companyName", merchantBaseInfo.getCompanyName());
            itemMap.put("companyId", String.valueOf(merchantBaseInfo.getId()));

            mapList.add(itemMap);
        }

        MemberSourceInfo memberSourceInfo = memberSourceInfoService.getById(matchOrderInfo.getUid());

        modelMap.put("realname", DesensitizedUtil.chineseName(memberSourceInfo.getRealname()));
        modelMap.put("idCard", DesensitizedUtil.idCardNum(memberSourceInfo.getIdcard(), 3,3));
        modelMap.put("mobile", DesensitizedUtil.mobilePhone(memberSourceInfo.getMobile()));
        modelMap.put("approveTime", LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME));

        modelMap.put("orderId", orderId);
        modelMap.put("itemMapList", mapList);

        return "approve";
    }




    /**
     * 淘金的协议
     */
    @RequestMapping(value = "/pubprotocol/{infoId}/{uid}.html")
    public String pubprotocol(@PathVariable("infoId") String infoId,
                               @PathVariable("uid") String uid,
                               ModelMap modelMap){

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(infoId);

        modelMap.put("companyName", merchantBaseInfo.getCompanyName());
        modelMap.put("companyId", String.valueOf(merchantBaseInfo.getId()));

        MemberSourceInfo memberSourceInfo = memberSourceInfoService.getById(uid);
        modelMap.put("realname", DesensitizedUtil.chineseName(memberSourceInfo.getRealname()));
        modelMap.put("idCard", DesensitizedUtil.idCardNum(memberSourceInfo.getIdcard(), 3,3));
        modelMap.put("mobile", DesensitizedUtil.mobilePhone(memberSourceInfo.getMobile()));
        modelMap.put("approveTime", LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME));

        return "pubprotocol";
    }

    /**
     *
     *
     * 商户自己的协议
     */
    @RequestMapping(value = "/priprotocol/{infoId}/{uid}.html")
    public String priprotocol(@PathVariable("infoId") String infoId,
                               @PathVariable("uid") String uid,
                               ModelMap modelMap){
        try {
            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(infoId);

            MemberSourceInfo memberSourceInfo = memberSourceInfoService.getById(uid);

            ProtocolParamResult paramResult = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                    .getProtocolResult(merchantBaseInfo, memberSourceInfo);

            modelMap.addAttribute("userInfo", paramResult.getUserInfo());
            modelMap.addAttribute("extInfo", paramResult.getExtInfo());

            return paramResult.getFilePath();
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return "pubprotocol";
    }

    /**
     * http://127.0.0.1:1779/page/protocol/qidai/82/8cd4cc38dda426accd181c08471603f6.html
     * http://apitest.koukoudai.shop/page/protocol/qidai/82/8cd4cc38dda426accd181c08471603f6.html
     * /protocol/qidai//.html
     * 商户自己的协议
     */
    @RequestMapping(value = "/protocol/qidai/{infoId}/{mobileMd5}.html")
    public String qidaiprotocol(@PathVariable("infoId") String infoId,
                              @PathVariable("mobileMd5") String mobileMd5,
                              ModelMap modelMap){
        try {
            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(infoId);

            MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectByMobileMd5(mobileMd5);
            ProtocolParamResult paramResult = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                    .getProtocolResult(merchantBaseInfo, memberSourceInfo);

            modelMap.addAttribute("userInfo", paramResult.getUserInfo());
            modelMap.addAttribute("extInfo", paramResult.getExtInfo());

            return paramResult.getFilePath();
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return "pubprotocol";
    }

    @RequestMapping(value = "/test.html")
    public String test(ModelMap modelMap){
        return "/priprotocol/chengyitong";
    }

    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Resource
    MerchantBaseInfoMapper merchantBaseInfoMapper;

    /**
     * 用户协议
     * http://127.0.0.1:1779/page/protocol/honghua?productId=282834494&phone=123
     * http://apitest.koukoudai.shop/page/protocol/honghua?productId=282834494&phone=123
     */
    @RequestMapping(value = "/protocol/honghua")
    public String userProtocol(@RequestParam(value = "productId",required = false) String productId,
                               @RequestParam(value = "phone", required = false) String phone,
                               @RequestParam(value = "username", required = false) String username,
                               @RequestParam(value = "idCard", required = false) String idCard,
                               ModelMap modelMap){
        String channelCode = "0KM34I"; // 小红花借款 渠道编号

        // TODO: 2023/8/23 访问条件判断
        if (ObjectUtil.isNotEmpty(productId)){
            // 产品id
            SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(channelCode, productId);

            if (ObjectUtil.isNotEmpty(pushResultInfo)){
                MerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.selectById(pushResultInfo.getInfoId());

                if (ObjectUtil.isNotEmpty(merchantBaseInfo)){
                    Map<String, String> itemMap = new HashMap<>();
                    itemMap.put("companyName", merchantBaseInfo.getCompanyName());
                    itemMap.put("companyId", String.valueOf(merchantBaseInfo.getId()));

                    List<Map<String, String>> mapList = new ArrayList<>();
                    mapList.add(itemMap);

                    modelMap.put("itemMapList", mapList);
                }
            }
        }

        modelMap.put("idCard", idCard);
        modelMap.put("mobile", phone);
        modelMap.put("username", username);
        modelMap.put("approveTime", LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME));

        return "approveHongHua";
    }


    public static void main(String[] args) {

        String url = "http://apitest.koukoudai.shop/page/protocol/qidai/{}";

        System.out.println(StrUtil.format(url, "85", "1726153329122324481"));

    }
}
